<?php


namespace Xy\Rbac\Services;


use Xy\Rbac\Repositories\RbacUserRoleRepository;

class RbacUserService {
    /**
     * 获取用户分页
     * @return array
     */
    public function getRabcUserPage() {
        $userPageQuery = \Xy\Rbac\Providers\RbacServiceProvider::getUserQuery();
        $this->_queryConditionDeal($userPageQuery);
        $userPageQuery->orderBy('id','desc');
        
        $pageInfo = [
            'list'        => [],
            'total_count' => 0,
        ];
        
        $pageInfo['total_count'] = $userPageQuery->count();
        if ($pageInfo['total_count']) {
            $this->_queryPageDeal($userPageQuery);
            $pageInfo['list'] = $userPageQuery->get();
        }
        
        return $pageInfo;
    }
    
    /**
     * 用户搜索条件处理
     *
     * @param $userPageQuery
     */
    protected function _queryConditionDeal($userPageQuery) {
        $conditionList = request()->get('conditions') ?? [];
        
        foreach ($conditionList as $conditionInfo) {
            if (
                is_array($conditionInfo)
                &&
                isset($conditionInfo['value']) && isset($conditionInfo['field_name']) && isset($conditionInfo['type'])
            ) {
                if ($conditionInfo['type'] == 3 && is_string($conditionInfo['value']) && trim($conditionInfo['value'])) {
                    $userPageQuery->where($conditionInfo['field_name'], 'LIKE', "%{$conditionInfo['value']}%");
                } elseif ($conditionInfo['type'] == 1) {
                    $userPageQuery->where($conditionInfo['field_name'], $conditionInfo['value']);
                }
            }
        }
    }
    
    /**
     * @param $userPageQuery
     */
    protected function _queryPageDeal($userPageQuery) {
        $pageInfo = request()->get('page_info', []);
        $page     = $pageInfo['page'] ?? 1;
        $perPage  = $pageInfo['per_page'] ?? 10;
        
        $userPageQuery->skip(($page - 1) * $perPage)->take($perPage);
    }
    
    /**
     * 获取用户已分配角色id列表
     *
     * @param $id
     *
     * @return \Illuminate\Support\Collection
     */
    public function getUserRoleIdList($id) {
        return RbacUserRoleRepository::getInstance()->getRoleByUserId($id)->pluck('role_id');
    }
    
    /**
     * 获取用户已分配角色id列表
     *
     * @param $id
     *
     * @return \Illuminate\Support\Collection
     */
    public function assignRole($id, $roleIdList) {
        //小操作，不进行事务
        RbacUserRoleRepository::getInstance()->delUserRoleRelativeByUserId($id);
        RbacUserRoleRepository::getInstance()->assignRolesToUser($id, $roleIdList);
    }
}